import Taro from '@tarojs/taro';
import { Toast } from '@/utils';

import { StorageKey } from '@/constants/storage';

type UploadFileOption = Omit<Taro.uploadFile.Option, 'url'> & {
  filePath: string;
  name?: string;
};

export const useUpload = () => {
  const uploadFile = (option: UploadFileOption): Promise<string> => {
    return new Promise((resolve, reject) => {
      Taro.uploadFile({
        ...option,
        url: `${process.env.BASE_URL}${process.env.BASE_API}/url/address`,
        header: {
          labToken: Taro.getStorageSync(StorageKey.TOKEN),
        },
        success(res) {
          if (res.statusCode === 200 && res.data) {
            const data = JSON.parse(res.data);
            resolve(data.success ? data.data : '');
          } else if (res.statusCode === 413) {
            Toast.info('文件大小超出限制');
            reject('文件大小超出限制');
          } else {
            Toast.info('上传失败');
            reject('上传失败');
          }
        },
        fail() {
          Toast.info('上传失败');
          reject('上传失败');
        },
      });
    });
  };

  /**
   * 批量上传文件
   * @param tempFiles 临时文件数组
   * @returns 文件地址数组
   */
  const uploadFiles = async (files: Taro.chooseMedia.ChooseMedia[]) => {
    try {
      const uploadTasks = files.map((file) =>
        uploadFile({
          filePath: file.tempFilePath,
          name: 'file',
        }),
      );

      const results = await Promise.all(uploadTasks);
      // 过滤掉上传失败的文件（返回false的情况）
      const successUrls = results.filter(
        (url): url is string => typeof url === 'string',
      );

      if (successUrls.length === 0) {
        Toast.info('所有文件上传失败');
        return [];
      }

      if (successUrls.length < files.length) {
        Toast.info('部分文件上传失败');
      }

      return successUrls;
    } catch (error) {
      Toast.info(error ?? '上传过程出错');
      return [];
    }
  };

  return {
    upload: uploadFile,
    uploadFiles,
  };
};
